package game.engine.base.anim

import game.engine.base.Node
import game.engine.base.Scene

// tweenManager
class TweenManager(val scene: Scene){
    private val lstTween = ArrayList<Tween>()
    private val newAddTween = ArrayList<Tween>()

    var inTweenUpdate = false
    fun update(dt:Float){
        inTweenUpdate = true

        for(i in 0 until lstTween.size){
            val tween = lstTween[i]

            // 节点可能已经被标记删除
            if (tween.target!!.willDestroy){
                tween.allEnd = true
                continue
            }

            // 可能以及处于删除状态
            if (tween.allEnd){
                continue
            }

            // TODO: 如果节点 visible 为  false, tween是否继续执行?
            // 这里继续执行
            tween.execute(dt)

            // 可能在  tween.execute 中已经删除了  target
            if (tween.target!!.willDestroy){
                tween.allEnd = true
            }else{
                if (tween.end){
                    if (tween.nextTween == null){
                        // all end
                        tween.allEnd = true
                    }else{
                        lstTween[i] = tween.nextTween!!
                        lstTween[i].target = tween.target
                    }
                }
            }
        }

        inTweenUpdate = false

        //  删除
        val iter = lstTween.iterator()
        while (iter.hasNext()){
            val tween = iter.next()
            if (tween.allEnd){
                iter.remove()
            }
        }

        lstTween.addAll(newAddTween)
        newAddTween.clear()
    }

    fun addTween(tween:Tween){
        if (inTweenUpdate){
            newAddTween.add(tween)
        }else{
            lstTween.add(tween)
        }
    }

    // 只进行标记
    fun removeTweenByNode(node: Node){
        lstTween.forEach { tween ->
            if (tween.target == node){
                tween.allEnd = true
            }
        }
        newAddTween.forEach { tween ->
            if (tween.target == node){
                tween.allEnd = true
            }
        }
    }

    fun release(){
        lstTween.clear()
        newAddTween.clear()
        inTweenUpdate = false
    }
}